from django.shortcuts import render,redirect,reverse
from repository import models
from backend.forms import ArticleForm,ArticleDetailForm


def article_list(request):

    all_artitle = models.Article.objects.all()
    return render(request,'backend/article_list.html',{'all_artitle':all_artitle})

def article_add(request):
    form_obj = ArticleForm()
    detail_from = ArticleDetailForm()
    title = '新增文章'
    if request.method == 'POST':
        detail_from = ArticleDetailForm(request.POST)
        if detail_from.is_valid():
            detail_from.save()
        # 将内容详情的id 保存到Article表的detail字段中
        qd = request.POST.copy() # 由于QueryDict instance is immutable 不可编辑类型
        qd['detail'] = detail_from.instance.pk
        form_obj = ArticleForm(data=qd,files=request.FILES)
        if form_obj.is_valid():
            form_obj.save()
            return redirect('backend:article_list')

        # 避免一张表写完数据，第二章表出错
        if detail_from.is_valid() and detail_from.instance:
            detail_from.instance.delete()

    return render(request, 'backend/article_form.html', {'title':title, 'form_obj':form_obj,'detail_from':detail_from})


def article_edit(request,pk):
    obj = models.Article.objects.filter(pk=pk).first()
    form_obj = ArticleForm(instance=obj)
    detail_from = ArticleDetailForm(instance=obj.detail)
    title = '编辑文章'
    if request.method == 'POST':
        detail_from = ArticleDetailForm(request.POST,instance=obj.detail)
        if detail_from.is_valid():
            detail_from.save()
        # 将内容详情的id 保存到Article表的detail字段中
        qd = request.POST.copy() # 由于QueryDict instance is immutable 不可编辑类型
        qd['detail'] = detail_from.instance.pk
        form_obj = ArticleForm(data=qd,files=request.FILES,instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            return redirect('backend:article_list')

    return render(request, 'backend/article_form.html', {'title':title, 'form_obj':form_obj,'detail_from':detail_from})


def article_del(request,pk):
    obj = models.Article.objects.filter(pk=pk).first()
    obj.detail.delete()
    return redirect('backend:article_list')